Skip to content

fix: complete build-provenance follow-ups (#1776–#1778) - #1789

Merged
dekobon merged 4 commits into
mainfrom
fix/batch-2026-11-02
Nov 4, 2026
Merged

dekobon merged 4 commits into
mainfrom
fix/batch-2026-11-02

Conversation

@dekobon

@dekobon dekobon commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Summary

Complete the three follow-ups deferred from PR #1780 / issue #1773. The branch has one commit per issue, followed by a lessons-learned commit.

  • grammars: gate the src/tree_sitter/ header watch in the vendored build.rs files #1778 — guard grammar header watches. Add check-grammar-build-watch and its self-tests. The gate discovers vendored grammar paths through [workspace].exclude and checks that each bindings/rust/build.rs retains the hand-maintained src/tree_sitter/ watch block. Its token comparison tolerates comments and formatting. Wire it into Make, pre-commit, and CI, and correct the documentation describing these build scripts as wholly generated.
  • cli: read the Mach-O LC_UUID and PE CodeView build ids for bca --version #1777 — read platform build IDs. Move the ELF reader into build_info/build_id/ and add bounded readers for thin little-endian 64-bit Mach-O LC_UUID and PE32/PE32+ CodeView GUID-plus-age records. PE uses bounded seek/read operations for records beyond the 64 KiB header. Preserve lowercase raw-byte hex output and fail-closed unavailable behavior; reject undersized ELF program-header strides. The build inputs: and build id: output labels remain unchanged.
  • hooks: agent hooks prefer target/release/bca, which #1773 made routinely stale #1776 — select a provenance-matching hook analyzer. Preserve explicit $BCA; otherwise prefer the first matching build-input digest among debug, release, and PATH candidates, then fall back to the newest local build and finally PATH. Resolve PATH candidates against the checkout and retain their absolute paths. Bound discovery to four seconds, cache it per checkout root per plugin event, record the selection reason, and raise the outer Claude hook slot to 15 seconds. Update the user-facing recipe and regression tests.
  • Extend lesson 91 with the self-scan filtering incident and add lesson 112 on test-double routing errors, incorporating independent review corrections.

Fixes #1778
Fixes #1777
Fixes #1776

Validation

Base: 296c9bed1285890d5bc071422bc2755783d71a47 (origin/main).
Head: 939c2c72313a0a4a1b1c9f035c3b9c9076d387c4.
Local environment: Linux, Rust 1.99.0, Node 25.9.0, Python 3.12.13.

  • Final reviewed working tree passed make pre-commit, with the canonical verdict BCA_GATE: pass (gate=pre-commit). The amended lessons commit was checked against the staged tree hash, so the published tree is the validated tree.
  • make self-scan-baseline-fresh: 0 added, 0 removed, 0 worsened, 0 improved after rebasing and squashing. Intermediate issue commits also passed compilation and baseline checks.
  • make self-scan-profile-parity: dev and release baselines were byte-identical on the integration tree before the subsequent main rebase; the post-rebase full gate and baseline-freshness check also passed.
  • 14 build-ID tests, including malformed/truncated inputs, PE records beyond the header bound, nonzero RVA translation, the debug-entry cap, and Linux dispatch. Synthetic Mach-O and PE fixtures run on Linux; cfg simulations covered macOS, Windows, and the unsupported-platform stub under library/all-target Clippy and tests. Native macOS/Windows execution remains for CI.
  • 29 grammar-watch self-tests and 71 hook/plugin tests. The latter were exercised with an explicit checkout-built BCA_TEST_BINARY, matching CI's configuration.
  • Recorded perturbations demonstrated that the regression tests detect the changed predicates. The documented Mach-O clamp-and-advance case preserves the tested rejection outcome and is not claimed as a detected defect.

Reproduction commands from the checkout:

make worktree-setup
make pre-commit
make self-scan-baseline-fresh
make self-scan-profile-parity
python3 -B -m unittest -q utils/check-grammar-build-watch-test.py
cargo test -p big-code-analysis-cli --all-features --lib build_id
cargo build -p big-code-analysis-cli
BCA_TEST_BINARY="$PWD/target/debug/bca" make plugin-test

Use bca.exe for the explicit binary path on Windows.

Review and limits

Each issue passed simplify-rust, rust-optimize, and audit-tests, followed by correctness, maximum-effort code review, performance, architecture, Astra, and under-reviewed-area passes. Findings were remediated and the fixes reviewed by Astra. Astra and Sol then reviewed the integration branch; Sol's timeout-headroom finding is included here. The lessons received a separate self-review and Astra review.

  • Universal/FAT Mach-O is intentionally unsupported. Missing linker IDs and unsupported images render unavailable; this field is informational.
  • cfg(any(<os>, test)) reader modules are pruned by the repository's test-excluding self-scan. That limitation is documented; suppression markers were checked with an explicit, unpruned nexits=5 invocation.

… build.rs files

#1773 added a block to each of the five vendored grammar build scripts
that `rerun-if-changed`-watches every file under `src/tree_sitter/`,
because a header-only edit otherwise left a stale parser object behind
a fresh `build inputs:` digest. No regeneration restores that block and
nothing noticed if it was dropped; AGENTS.md even described the files
as boilerplate a regeneration replaces wholesale.

`utils/check-grammar-build-watch.py` is a new gate rather than an
assertion in `check-grammar-crate.py` (the grammar-bump metric-diff
driver, listed among the non-gates). Its crate list comes from the
`[workspace].exclude` entries naming `tree-sitter` — a substring, as
`check-excluded-manifests.py` matches, so a sixth crate laid out under
its published `bca-tree-sitter-*` name is in scope. The issue's literal
`rerun-if-changed=src/tree_sitter` exists in no file (the path is
interpolated at build time), and a token-pair check admits a file that
names the path but never watches it, so the gate lexes `build.rs` —
strings, raw strings, escaped-newline continuations, char literals,
lifetimes, nested block comments — and requires the canonical block as
a contiguous token run, printing a token-aligned diff against the
closest region on failure. A missing `build.rs` fails (that is the
regeneration-dropped-it case), as does a non-UTF-8 one, a missing
manifest and a malformed exclude list.

Wired at all seven sites: Makefile help, public targets, `.PHONY`,
`lint`, `_pc-all`, `_ci-all`; `.pre-commit-config.yaml` hooks whose
`files:` cover `Cargo.toml`, any `*tree-sitter*/bindings/rust/build.rs`
and the script pair; explicit `ci.yml` steps beside the safety-doc-pin
pair. AGENTS.md's lint-exemption rationale now carves out `build.rs`,
and `check-excluded-manifests.py`'s echo of that rationale matches.

Self-test: 29 rows over scratch layouts — block deleted, commented out,
loop deleted, emission replaced, parser.c-only, `build.rs` missing,
directory missing, published-name crate, reflowed block, each lexer
rule — plus the live tree. Perturbations: the block deleted from
`tree-sitter-mozjs` → the gate names that crate; `main()` stubbed →
13 of 29 red; each lexer rule removed → its named row red; prefix in
place of substring discovery → only the published-name row red.

Reviewed by simplify-rust, rust-optimize, audit-tests, six reviewers
and an astra closure check; every finding fixed (one medium, the
prefix-vs-substring discovery; twelve lows, including an
escaped-newline lexer regression the closure check caught).

Fixes #1778
@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.08497% with 32 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.33%. Comparing base (296c9be) to head (ead8474).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...ig-code-analysis-cli/src/build_info/build_id/pe.rs 72.61% 0 Missing and 23 partials ⚠️
...code-analysis-cli/src/build_info/build_id/macho.rs 81.81% 0 Missing and 4 partials ⚠️
...g-code-analysis-cli/src/build_info/build_id/elf.rs 72.72% 0 Missing and 3 partials ⚠️
...g-code-analysis-cli/src/build_info/build_id/mod.rs 97.14% 0 Missing and 1 partial ⚠️
big-code-analysis-cli/src/build_info/mod.rs 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1789      +/-   ##
==========================================
- Coverage   98.35%   98.33%   -0.03%     
==========================================
  Files         388      391       +3     
  Lines      116494   116610     +116     
  Branches   116059   116175     +116     
==========================================
+ Hits       114583   114673      +90     
  Misses       1219     1219              
- Partials      692      718      +26     
Flag Coverage Δ
python 100.00% <ø> (ø)
rust 98.33% <79.08%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
big-code-analysis-cli/src/build_info/digest.rs 97.45% <ø> (ø)
...g-code-analysis-cli/src/build_info/build_id/mod.rs 97.14% <97.14%> (ø)
big-code-analysis-cli/src/build_info/mod.rs 85.71% <0.00%> (ø)
...g-code-analysis-cli/src/build_info/build_id/elf.rs 74.46% <72.72%> (ø)
...code-analysis-cli/src/build_info/build_id/macho.rs 81.81% <81.81%> (ø)
...ig-code-analysis-cli/src/build_info/build_id/pe.rs 72.61% <72.61%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

`build id:` printed `unavailable` on macOS and Windows because only the
ELF reader existed. `build_info/elf.rs` becomes
`build_info/build_id/{mod,elf,macho,pe}.rs`: `mod.rs` dispatches per
OS and owns the shared primitives — `HEAD_BYTES`, `read_head` /
`read_at`, one `hex_lower` (`digest.rs` keeps its own for the
`build.rs` `#[path]` share), the LE width readers — each gated
`any(linux, macos, windows, test)` so an unsupported target compiles
with no dead items under `-D warnings`. Each reader mirrors the ELF
shape: `current()` gated on its OS only, the parser in `mod reader`
under `any(<os>, test)`.

`macho.rs` reads the 16-byte `LC_UUID` of a thin little-endian 64-bit
image, the shape `aarch64-apple-darwin` ships. The walk is bounded by
`sizeofcmds` and the slice; a `cmdsize` under 8 inverts the body range
so the read fails rather than re-reading one command `ncmds` times.
`MH_MAGIC`, `MH_CIGAM_64` and `FAT_MAGIC` read as absent — universal
binaries are a documented non-goal, since nothing here is `lipo`d.

`pe.rs` reads the 20 bytes after `RSDS` — the GUID as stored plus the
age — of the first `CodeView` entry, for PE32 and PE32+. The directory
and record routinely sit past 64 KiB, so the parser is two-stage and
takes its second-stage reader as a closure, which is also how the
fixtures drive it without files. Entry 6 must lie inside the declared
`SizeOfOptionalHeader`, the directory's RVA inside one section's
`SizeOfRawData`; only complete 28-byte entries are walked, capped at
64 — the one bound between a declared 4 GiB `size` and a `Vec` of that
capacity; a non-`RSDS` or short entry is skipped for a later one.

The ELF reader now refuses an `e_phentsize` below 56: `phentsize = 0`
with `phnum = 65535` aliased every index onto one `PT_NOTE` and cost
272 ms against 31 µs. Rendering is lowercase hex of the raw bytes for
all three. STABILITY.md names the formats, the per-format lengths
(including lld's 8-byte `fast` default before LLVM 19) and the
`unavailable` cases: FAT Mach-O, `-no_uuid`, no `CodeView`, ELF
without `--build-id`.

The readers' `any(<os>, test)` gate is pruned by `bca check
--exclude-tests`, so they sit outside the self-scan and their
`bca: suppress(nexits)` markers hold nothing there; `elf.rs`'s module
doc says so and names the unpruned command, under which all three
measure clean (a fn and the closure inside it are separate spaces and
each carries a marker).

Tests: 14 in `build_id_tests.rs` — pinned-hex positives for both
formats, the PE32+ one with its directory and record past 64 KiB, a
PE32 one, and a fixture whose section is mapped 0x2000 above its file
offset behind an unrelated section so the RVA translation is
observable; every malformed shape; truncation sweeps over every prefix;
the 65-entry cap; a Linux-gated test that the dispatcher reaches the
ELF reader. Perturbation sweep: 17 guards, 16 caught by the test that
names each; the miss is the documented Mach-O `cmdsize < 8` non-guard.
cfg rotation on this Linux host — the crate compiled as if for macOS,
Windows and FreeBSD — clean under clippy `--lib`, `--all-targets` and
the tests. macOS and Windows cannot be exercised natively here; that
and the fixtures are the evidence.

Reviewed by simplify-rust, rust-optimize, audit-tests, six reviewers
and two astra closure checks; every finding fixed or rejected with a
reason: the inner `cfg(any(os, test))` on `mod reader` is kept (it
carries the self-scan note and mirrors #1780's shape); `build_id` stays
`pub(crate)` for the `cfg(test)` re-export; three `.map(hex_lower)`
sites, the ELF test naming and re-opening the executable per PE read
are cosmetic.

Fixes #1777
Since #1773 the self-scan recipes build `bca` under the dev profile and
nothing in the ordinary workflow builds release, so `target/release/bca`
was routinely a binary from some earlier day — and it was what the
per-edit hook ran first, reporting offenders a different `bca` computed
than `make self-scan`.

`analyzer()` in `.claude/hooks/bca-common.mjs` now resolves, in order:
`$BCA` unprobed; the first of `target/debug/bca`, `target/release/bca`
and PATH `bca` whose `--version` reports a `build inputs:` digest equal
to the one `utils/self_scan_digest.py` computes over the checkout — the
same test `utils/self-scan-bca.py` applies; else the newest local build
by mtime; else PATH `bca`. It returns `{ path, reason }`: the Claude
hook records the reason as `analyzerReason` in its one health line and
the OpenCode plugin appends it to its `[bca-check] analyzer=` note and
persists it.

Trust boundary: the digest script is resolved relative to the hook
module, never to the checkout root, because `checkContext` can hand
over a nested checkout and that checkout must not supply Python the
parent's hook runs (`BCA_DIGEST_SCRIPT` is the tests' seam). PATH
entries are resolved against the checkout — an empty entry is the
checkout, as `spawn` reads it — and the resolved file is the candidate,
so the binary that answered `--version` is the one the check runs and
the one the health line names. Probing candidates executes them, which
is the trust the old order already granted `target/release/bca`.

Discovery shares one 4 s budget, chained to the caller's signal, so the
digest plus three probes at the 3 s per-process TIMEOUT cannot consume
the hook's slot; the plugin resolves once per checkout root per event.
Every digest failure — missing python3, a non-zero exit with its first
stderr line, an un-stat-able script, a rejected spawn — is a recorded
reason, never a thrown error. The bounded stages (git 3 s, discovery
4 s, the check 3 s) sum to 10 s, so `.claude/settings.json` registers a
15 s slot; the book example and the pinned test follow.

Tests: 71 across the two `node --test` files, on all three CI OSes —
fakes are JS files routed through the fixture's spawn patch by the
fixture's exact local paths, since a shape route captured the real
`target/debug/bca` CI hands the same suite through `BCA_TEST_BINARY`.
Matching debug over release and the reverse; matching PATH over stale
locals; a relative PATH entry resolved against the checkout and
reported by file; newest-by-mtime both orders; PATH when no local
build; `$BCA` never probed; failing and missing python3; an
un-stat-able digest script; a stalled `--version` abandoned at the
budget, decided on output not the clock; SIGTERM during discovery; a
PATH symlink to a local build probed once; the plugin's once-per-event
digest. Perturbation sweep: 13 branches, each caught by exactly the
test that names it.

AGENTS.md and the book recipe (two bullets that documented the old
order) describe the new order, `analyzerReason`, and the degraded
order for a hook copied without the digest script.

Reviewed by simplify-rust, rust-optimize, audit-tests, six reviewers,
an astra closure check and the whole-branch review; every finding
fixed or rejected with a reason: the plugin test's layered spawn mock
is benign (its fallthrough is the real spawn; 71/71 in every order)
and `Promise.all` over the stat stages saves ~2 ms.

Fixes #1776
Extend lesson 91 with the production build-id readers excluded by their test-inclusive cfg gates (#1777). Add lesson 112 on test doubles intercepting real artifacts or missing calls after executable resolution changes (#1776).
@dekobon
dekobon force-pushed the fix/batch-2026-11-02 branch from 939c2c7 to ead8474 Compare November 3, 2026 23:26
@dekobon
dekobon merged commit ead8474 into main Nov 4, 2026
57 of 59 checks passed
@dekobon
dekobon deleted the fix/batch-2026-11-02 branch November 4, 2026 01:02

This branch was previously deployed

1 inactive deployment
github-pages — ead8474a Deployed Nov 4, 2026 by dekobon via deploy to GitHub Pages #949
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant